package com.wskj.workbench.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wskj.common.core.domain.entity.SysUser;
import com.wskj.common.core.domain.entity.TbUserTiktok;
import com.wskj.common.core.mybatisplus.core.ServicePlusImpl;
import com.wskj.common.core.page.PagePlus;
import com.wskj.common.core.page.TableDataInfo;
import com.wskj.common.utils.common.AssertUtils;
import com.wskj.common.utils.common.PageUtils;
import com.wskj.common.utils.common.SecurityUtils;
import com.wskj.service.asyc.IAsyncService;
import com.wskj.system.service.ISysConfigService;
import com.wskj.system.service.ISysUserService;
import com.wskj.workbench.bo.web.TbTiktokOrderAddBo;
import com.wskj.workbench.bo.web.TbTiktokOrderEditBo;
import com.wskj.workbench.bo.web.TbTiktokOrderQueryBo;
import com.wskj.workbench.component.AsyncService;
import com.wskj.workbench.domain.TbTiktokOrder;
import com.wskj.workbench.domain.TbUserWalletDetail;
import com.wskj.workbench.enums.UserTypeEnum;
import com.wskj.workbench.enums.UserWalletDetailRecommendTypeEnum;
import com.wskj.workbench.mapper.TbTiktokOrderMapper;
import com.wskj.workbench.service.ITbTiktokOrderService;
import com.wskj.workbench.service.ITbUserTiktokService;
import com.wskj.workbench.service.ITbUserWalletDetailService;
import com.wskj.workbench.vo.web.TbTiktokOrderVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 抖音订单Service业务层处理
 *
 * @author wskj
 * @date 2024-09-24
 */
@Service
@AllArgsConstructor
public class TbTiktokOrderServiceImpl extends ServicePlusImpl<TbTiktokOrderMapper, TbTiktokOrder> implements ITbTiktokOrderService {


    private final ITbUserTiktokService tbUserTiktokService;

    private final ISysUserService sysUserService;

    private final ITbUserWalletDetailService tbUserWalletDetailService;

    private final ISysConfigService sysConfigService;

    private final AsyncService asyncService;

    @Override
    public TbTiktokOrderVo queryById(Long id) {
        return getVoById(id, TbTiktokOrderVo.class);
    }

    @Override
    public TableDataInfo<TbTiktokOrderVo> queryPageList(TbTiktokOrderQueryBo bo) {
        PagePlus<TbTiktokOrder, TbTiktokOrderVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), TbTiktokOrderVo.class);
        return PageUtils.buildDataInfo(result);
    }

    @Override
    public List<TbTiktokOrderVo> queryList(TbTiktokOrderQueryBo bo) {
        return listVo(buildQueryWrapper(bo), TbTiktokOrderVo.class);
    }

    private LambdaQueryWrapper<TbTiktokOrder> buildQueryWrapper(TbTiktokOrderQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TbTiktokOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(StrUtil.isNotBlank(bo.getInitiationDate()), TbTiktokOrder::getInitiationDate, bo.getInitiationDate());
        lqw.eq(StrUtil.isNotBlank(bo.getVerifiTime()), TbTiktokOrder::getVerifiTime, bo.getVerifiTime());
        lqw.eq(StrUtil.isNotBlank(bo.getCouponCode()), TbTiktokOrder::getCouponCode, bo.getCouponCode());
        lqw.eq(StrUtil.isNotBlank(bo.getBillId()), TbTiktokOrder::getBillId, bo.getBillId());
        lqw.eq(StrUtil.isNotBlank(bo.getMerchantId()), TbTiktokOrder::getMerchantId, bo.getMerchantId());
        lqw.like(StrUtil.isNotBlank(bo.getMerchantName()), TbTiktokOrder::getMerchantName, bo.getMerchantName());
        lqw.eq(StrUtil.isNotBlank(bo.getGroupId()), TbTiktokOrder::getGroupId, bo.getGroupId());
        lqw.like(StrUtil.isNotBlank(bo.getGroupName()), TbTiktokOrder::getGroupName, bo.getGroupName());
        lqw.eq(bo.getProPrice() != null, TbTiktokOrder::getProPrice, bo.getProPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getContentType()), TbTiktokOrder::getContentType, bo.getContentType());
        lqw.eq(StrUtil.isNotBlank(bo.getContentId()), TbTiktokOrder::getContentId, bo.getContentId());
        lqw.eq(StrUtil.isNotBlank(bo.getContentTitle()), TbTiktokOrder::getContentTitle, bo.getContentTitle());
        lqw.eq(StrUtil.isNotBlank(bo.getTiktokUid()), TbTiktokOrder::getTiktokUid, bo.getTiktokUid());
        lqw.eq(StrUtil.isNotBlank(bo.getTiktokNo()), TbTiktokOrder::getTiktokNo, bo.getTiktokNo());
        lqw.eq(StrUtil.isNotBlank(bo.getTiktokNick()), TbTiktokOrder::getTiktokNick, bo.getTiktokNick());
        lqw.eq(bo.getGmvPrice() != null, TbTiktokOrder::getGmvPrice, bo.getGmvPrice());
        lqw.eq(bo.getTotalPrice() != null, TbTiktokOrder::getTotalPrice, bo.getTotalPrice());
        lqw.eq(bo.getExpendPrice() != null, TbTiktokOrder::getExpendPrice, bo.getExpendPrice());
        lqw.eq(bo.getActualPrice() != null, TbTiktokOrder::getActualPrice, bo.getActualPrice());
        lqw.eq(StrUtil.isNotBlank(bo.getCommissionType()), TbTiktokOrder::getCommissionType, bo.getCommissionType());
        lqw.eq(StrUtil.isNotBlank(bo.getOrderId()), TbTiktokOrder::getOrderId, bo.getOrderId());
        lqw.eq(StrUtil.isNotBlank(bo.getOrderTime()), TbTiktokOrder::getOrderTime, bo.getOrderTime());
        lqw.eq(StrUtil.isNotBlank(bo.getFollowPerson()), TbTiktokOrder::getFollowPerson, bo.getFollowPerson());
        lqw.eq(StrUtil.isNotBlank(bo.getSfSettlement()), TbTiktokOrder::getSfSettlement, bo.getSfSettlement());
        lqw.eq(StrUtil.isNotBlank(bo.getDelFlag()), TbTiktokOrder::getDelFlag, bo.getDelFlag());


        // 如果不是超级管理员 需要查询所有下级用户列表
        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {

            SysUser sysUser = sysUserService.selectUserById(SecurityUtils.getUserId());

            lqw.in(ObjectUtil.isNotEmpty(sysUser), TbTiktokOrder::getCreateBy, sysUser.getUserId());

        }
        lqw.orderByDesc(TbTiktokOrder::getCreateTime);

        return lqw;
    }

    @Override
    public Boolean insertByAddBo(TbTiktokOrderAddBo bo) {
        TbTiktokOrder add = BeanUtil.toBean(bo, TbTiktokOrder.class);
        validEntityBeforeSave(add);
        return save(add);
    }

    @Override
    public Boolean updateByEditBo(TbTiktokOrderEditBo bo) {
        TbTiktokOrder update = BeanUtil.toBean(bo, TbTiktokOrder.class);
        validEntityBeforeSave(update);
        return updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TbTiktokOrder entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return removeByIds(ids);
    }

    @Override
    public String importTbTiktokOrder(List<TbTiktokOrderVo> tbTiktokOrderList) {
        AssertUtils.isTrue(CollectionUtils.isNotEmpty(tbTiktokOrderList), "导入数据不能为空");
        int successNum = 0;
        List<TbTiktokOrder> orderList = new ArrayList<>();
        for (TbTiktokOrderVo tbTiktokOrder : tbTiktokOrderList) {
//            // 劵码中去掉\t
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getCouponCode())) {
//                tbTiktokOrder.setCouponCode(tbTiktokOrder.getCouponCode().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getBillId())) {
//                tbTiktokOrder.setBillId(tbTiktokOrder.getBillId().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getMerchantId())) {
//                tbTiktokOrder.setMerchantId(tbTiktokOrder.getMerchantId().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getGroupId())) {
//                tbTiktokOrder.setGroupId(tbTiktokOrder.getGroupId().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getContentId())) {
//                // 内容id
//                tbTiktokOrder.setContentId(tbTiktokOrder.getContentId().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getTiktokUid())) {
//                // 达人uid
//                tbTiktokOrder.setTiktokUid(tbTiktokOrder.getTiktokUid().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getTiktokNo())) {
//                tbTiktokOrder.setTiktokNo(tbTiktokOrder.getTiktokNo().replace("\t", ""));
//            }
//            if (ObjectUtil.isNotEmpty(tbTiktokOrder.getOrderId())) {
//                tbTiktokOrder.setOrderId(tbTiktokOrder.getOrderId().replace("\t", ""));
//            }


            TbTiktokOrder add = BeanUtil.toBean(tbTiktokOrder, TbTiktokOrder.class);
////            // 如果总金额为0 则忽略本条记录不参与计算
//            if (add.getTotalPrice().compareTo(BigDecimal.ZERO) == 0) {
//                continue;
//            }
//            // 判断分账单id是否存在 如果存在则跳过
//            long count = count(Wrappers.lambdaQuery(TbTiktokOrder.class).eq(TbTiktokOrder::getBillId, tbTiktokOrder.getBillId()));
//            if (count != 0) {
//                continue;
//            }
//            //  判断抖音号是否存在 不存在跳过
//            long count1 = tbUserTiktokService.count(Wrappers.lambdaQuery(TbUserTiktok.class).eq(TbUserTiktok::getTikUid, tbTiktokOrder.getTiktokUid()));
//            if (count1 == 0) {
//                continue;
//            }
            orderList.add(add);
            successNum++;
        }
        // 批量保存订单
        if (ObjectUtil.isNotEmpty(orderList)) {
            // 异步处理分佣
            asyncService.handleCommission(orderList);
        }
        String msg = String.format("导入完成，共计 %d 条数据，成功 %d 条！", tbTiktokOrderList.size(), successNum);
        if (successNum != tbTiktokOrderList.size()) {
            msg = msg + String.format("失败 %d 条！", tbTiktokOrderList.size() - successNum);
        }
        return msg;
    }
}
